package com.lt.flashcard.view;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;

import com.lt.flashcard.Utility;
import com.lt.flashcard.bind.ConstraintValidator;
import com.lt.flashcard.bind.UniqueAccountValidator;
import com.lt.flashcard.bind.UniqueEmailValidator;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.EmailService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class RegisterCtrl {

	private String username;
	private String email;
	private String password;
	private String re_pass;
	private UniqueAccountValidator uniqueaccount;
	private UniqueEmailValidator uniqueemail;
	private ConstraintValidator constraintvalidator;
	
	@Init
	public void init() {
		if(Utility.isLogin())
			Utility.redirect("/wordlist.zul", false);
		
		uniqueaccount = new UniqueAccountValidator();
		uniqueemail = new UniqueEmailValidator();
		constraintvalidator = new ConstraintValidator();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRe_pass() {
		return re_pass;
	}

	public void setRe_pass(String re_pass) {
		this.re_pass = re_pass;
	}
	
	@Command
	public void register() {
		UserService srv = Repository.getInstance().getUserService();
		try {
			User user = new User(username.toLowerCase(), password, email.toLowerCase());
			user.setBlock(0);
			user.setActivation("");
			user.setExpiredate(null);
			srv.save(user);
			
			EmailService esrv = Repository.getInstance().getEmailService();
			esrv.sendEmailWelcome(username.toLowerCase(), email.toLowerCase());
			
			AAService asrv = Repository.getInstance().getAAService();
			asrv.doLogin(username.toLowerCase(), user.getPassword(), false, false);
			
			Utility.redirect("thanksregister.zul", true);
		}
		catch (Exception e) {
		}
	}

	public UniqueAccountValidator getUniqueaccount() {
		return uniqueaccount;
	}

	public void setUniqueaccount(UniqueAccountValidator uniqueaccount) {
		this.uniqueaccount = uniqueaccount;
	}

	public ConstraintValidator getConstraintvalidator() {
		return constraintvalidator;
	}

	public void setConstraintvalidator(ConstraintValidator constraintvalidator) {
		this.constraintvalidator = constraintvalidator;
	}
	
	private void sendEmail(String activeCode, Date date) throws UnknownHostException {
		Properties props = System.getProperties();
		props.put("mail.smtp.host", Utility.getConfiguration("com.lt.flashcard.smtp_host", ""));
		props.put("mail.smtp.socketFactory.port", Utility.getConfiguration("com.lt.flashcard.smtp_port", ""));
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", Utility.getConfiguration("com.lt.flashcard.smtp_port", ""));
		
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(Utility.getConfiguration("com.lt.flashcard.smtp_account", ""),
								Utility.getConfiguration("com.lt.flashcard.smtp_password", ""));
					}
				});
		
		try {
			String expire = Utility.formatDate(date, "dd-MM-yyyy");
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("test@lactien.com"));
			message.setRecipients(Message.RecipientType.TO,	InternetAddress.parse(email));
			message.setSubject("Flashcard: Activation account");
			String codeUrl = Utility.getConfiguration("com.lt.flashcard.serverurl", "") + "/activation.zul?code=" + activeCode;
			String loginUrl = Utility.getConfiguration("com.lt.flashcard.serverurl", "") + "/login.zul";
			String body = "<p>Dear " + username + ",</p>" + 
							"<p>Thank you for registering at Blueup Flashcard. Your account is created and must be activated before you can use it.</p>" +
							"<p>To activate the account click on the following link or copy-paste it in your browser:</p>" + 
							"<p><a href='" + codeUrl + "' target='_blank'>"+ codeUrl + "</a></p>" + 
							"<p>After activation you may login to <a href='" + loginUrl + "'>"+ loginUrl + "</a> using the following username and password:<br/><br/>Username: " + username + "<br/>Password: " + password + "</p>" +
							"<p>Date expire to activation: " + expire + "</p>";
			
			message.setContent(body, "text/html");
			Transport.send(message);
			
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}

	public UniqueEmailValidator getUniqueemail() {
		return uniqueemail;
	}

	public void setUniqueemail(UniqueEmailValidator uniqueemail) {
		this.uniqueemail = uniqueemail;
	}
}
